package com.anhuanjia.tools.eao.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.util.StringUtils;

import com.anhuanjia.bean.MhBranch;
import com.anhuanjia.bean.MhResource;
import com.anhuanjia.tools.eao.bean.CrmCompany;
import com.anhuanjia.tools.eao.bean.EaoIsEngineer;
import com.anhuanjia.tools.eao.bean.EaoTof;
import com.anhuanjia.tools.eao.beanvo.EaoMemberVo;
import com.anhuanjia.tools.eao.beanvo.EaoPublicityMemberVo;
import com.efastsoft.bean.CrmCustomerInfo;
import com.efastsoft.bean.CrmPeople;
import com.efastsoft.bean.EcMember;
import com.efastsoft.framework.Member;
import com.efastsoft.framework.UIFacade;
import com.efastsoft.framework.annotation.Alias;
import com.efastsoft.framework.annotation.Priv;
import com.efastsoft.framework.annotation.Priv.LoginType;
import com.efastsoft.framework.collection.Mapx;
import com.efastsoft.framework.data.DataRow;
import com.efastsoft.framework.data.DataTable;
import com.efastsoft.framework.data.Q;
import com.efastsoft.framework.data.Transaction;
import com.efastsoft.framework.security.PasswordUtil;
import com.efastsoft.framework.utility.StringUtil;
import com.efastsoft.member.bl.MemberBL;
import com.efastsoft.platform.util.NoUtil;

@Alias(value = "member")
public class MemberUI extends UIFacade {
	/**
	 * 添加一级账号人员
	 */
	@Priv(loginType = LoginType.Member)
	public void addEntMember() {
		Transaction transaction = new Transaction();
		String Mobile = $V("Mobile");
		String FullName = $V("UserName");
		String Type = $V("Type");//0更新1新增
		if (StringUtil.isNotEmpty(Mobile)) {
			DataTable dt = new Q(" SELECT * FROM Ec_Member where  Mobile = ? ", Mobile).fetch();
			if (dt.getRowCount() != 0) {
				EcMember em = new EcMember();
				em.setValue(dt.get(0));
				if (em.getType().equals("Ent")) {
					s("该账号是已有一级账号");
				} else {
					s("该账号已存在是否更改为一级账号");
				}
			} else {
				s("该账号不存在请创建");
			}
			if ("0".equals(Type)) {
				Mapx<String, Object> mdata = new Mapx<String, Object>();     
			    mdata.put("SiteID", 1);
			    mdata.put("Status", "Y");
			    mdata.put("Mobile", Mobile);
			    mdata.put("Type", "Ent");
			    mdata.put("Source", "BA");
			    mdata.put("AddTime", new Date());   	
			    EcMember member = MemberBL.update(dt.get(0).getString("UserName"), mdata, transaction);
			    
			    CrmPeople people = new CrmPeople();
			    people.setID(member.getID());    
			    if(people.fill()){
			    	people.setFullName(member.getRealName());     
				    people.setMobile(member.getMobile());
				    people.setAddTime(new Date());
				    transaction.update(people);	
			    }else{
			    	people.setFullName(member.getRealName());     
				    people.setMobile(member.getMobile());
				    people.setAddTime(new Date());
				    transaction.insert(people);
			    }
				
			    CrmCompany company = new CrmCompany();
				company.setID(member.getID());
				if(company.fill()){
					company.setFullName(FullName);
					company.setContactPhone(Mobile);
					transaction.update(company);
				}else{
					company.setFullName(FullName);
					company.setContactPhone(Mobile);
					transaction.insert(company);
				}
				
				MhBranch branch = new MhBranch();
				branch.setValue(this.Request);
				branch.setSiteID(0L);
				branch.setCompany(member.getID());
				branch.setID(NoUtil.getMaxID("MhBranchID"));
				branch.setBranchInnerCode(NoUtil.getMaxNo("MBICode_" + branch.getCompany(), 4));
				branch.setParentInnerCode("0");
				branch.setTreeLevel(1L);
				branch.setName(FullName);
				branch.setCompanyType("0");
				branch.setIsLeaf("Y");
				dt = (new Q("select * from Mh_Branch where Company=? order by Orderflag",
						new Object[] { branch.getCompany() })).fetch();
				String orderflag = "";
				if (dt != null && dt.getRowCount() > 0) {
					orderflag = dt.getString(dt.getRowCount() - 1, "OrderFlag");
				} else {
					orderflag = "0";
				}
				transaction.add(new Q("update Mh_Branch set Orderflag=Orderflag+1 where Company=? and Orderflag>?",
						new Object[] { branch.getCompany(), orderflag }));
				branch.setOrderFlag(orderflag + 1);
				branch.setAddTime(new Date());
				branch.setAddUser(Member.getUID());
				
				
				EaoTof tof = new EaoTof();
				tof.setBranchId(branch.getBranchInnerCode());
				tof.setCompanyId(member.getID().toString());
				tof.setTof("0");
				
				
				transaction.insert(tof);
				transaction.insert(branch);
				
				// 根据Member id查询Resource是否存在
				DataTable resource = new Q(" select * from Mh_Resource where Member =  ? ", member.getID()).fetch();
				MhResource mhResource = new MhResource();
				if (resource.getRowCount() != 0) {
					for (DataRow dataRow : resource) {
						mhResource.setValue(dataRow);
						transaction.delete(mhResource);
					}
				}
				// 根据Resource查询是否存在职位
				DataTable exists = new Q(
						" select * from Mh_Resource as re,eao_is_engineer as ie, eao_Position as po where re.Member = ie.Member and ie.IsEngineer = po.id and re.Member =  ? ",
						mhResource.getMember()).fetch();
				if (exists.getRowCount() != 0) {
					// 删除关系表
					Q deleteExists = new Q(" DELETE FROM eao_is_engineer WHERE Member = ?", mhResource.getMember());
					transaction.add(deleteExists);
				}

				if (transaction.commit()) {
					s("成功修改为一级账号");
				} else {
					f("修改为一级账号失败");
				}
			} else if ("1".equals(Type)) {
				if (StringUtil.isNotEmpty(FullName)) {
					Mapx<String, Object> mdata = new Mapx<String, Object>();     
				    mdata.put("Password", "123456");
				    mdata.put("SiteID", 1);
				    mdata.put("Status", "Y");
				    mdata.put("Mobile", Mobile);
				    mdata.put("Type", "Ent");
				    mdata.put("Source", "BA");
				    mdata.put("AddTime", new Date());   	
				    
				    EcMember member = MemberBL.insert(UUID.randomUUID().toString().replace("-", ""), mdata, transaction);
				    CrmPeople people = new CrmPeople();
				    people.setID(member.getID());   
				    if(people.fill()){
				    	people.setFullName(member.getRealName());     
					    people.setMobile(member.getMobile());
					    people.setAddTime(new Date());
					    transaction.update(people);
				    }else{
				    	people.setFullName(member.getRealName());     
					    people.setMobile(member.getMobile());
					    people.setAddTime(new Date());
					    transaction.insert(people);
				    }
				   
				    CrmCustomerInfo info = new CrmCustomerInfo();
				    info.setID(member.getID());
				    if (info.fill()) {
					     info.setFullName(FullName);
					     info.setCustType(member.getType());
					     info.setVerified(0);
					     info.setModifyTime(new Date());
					     transaction.update(info);
				    }else{
				    	 info.setFullName(FullName);
					     info.setCustType(member.getType());
					     info.setVerified(0);
					     info.setAddTime(new Date());
						 transaction.insert(info);
				    }
				    
				    CrmCompany com = new CrmCompany();
				    com.setID(member.getID());
				    if (com.fill()) {
				     // 更新
				     com.setFullName(FullName);
				     com.setContactPhone(Mobile);
				     com.setVerified("1");
				     com.setModifyTime(new Date());
				     transaction.update(com);
				    }else{
			    	 // 添加
				     com.setFullName(FullName);
				     com.setContactPhone(Mobile);
				     com.setVerified("1");
				     com.setAddTime(new Date());
				     transaction.insert(com);
				    }
				    
					MhBranch branch = new MhBranch();
					branch.setValue(this.Request);
					branch.setSiteID(0L);
					branch.setCompany(member.getID());
					branch.setID(NoUtil.getMaxID("MhBranchID"));
					branch.setBranchInnerCode(NoUtil.getMaxNo("MBICode_" + branch.getCompany(), 4));
					branch.setParentInnerCode("0");
					branch.setTreeLevel(1L);
					branch.setName(FullName);
					branch.setCompanyType("0");
					branch.setIsLeaf("Y");
					branch.setType("0");
					dt = (new Q("select * from Mh_Branch where Company=? order by Orderflag",
							new Object[] { branch.getCompany() })).fetch();
					String orderflag = "";
					if (dt != null && dt.getRowCount() > 0) {
						orderflag = dt.getString(dt.getRowCount() - 1, "OrderFlag");
					} else {
						orderflag = "0";
					}
					transaction.add(new Q("update Mh_Branch set Orderflag=Orderflag+1 where Company=? and Orderflag>?",
							new Object[] { branch.getCompany(), orderflag }));
					branch.setOrderFlag(orderflag + 1);
					branch.setAddTime(new Date());
					branch.setAddUser(Member.getUID());
					
					EaoTof tof = new EaoTof();
					tof.setBranchId(branch.getBranchInnerCode());
					tof.setCompanyId(member.getID().toString());
					tof.setTof("0");
					
					transaction.insert(branch);
					transaction.insert(tof);
					if (transaction.commit()) {
						s("一级账号创建成功");
					} else {
						f("一级账号创建失败");
					}
				} else {
					f("请输入用户名");
				}
			}
		}
	}

	/**
	 * 登录人的信息
	 */
	@Priv(loginType = LoginType.Member)
	public void findOne() {
		Long id = Member.getUID();
		if (id != null) {
			EaoMemberVo m = new EaoMemberVo();
			m.setUserName(Member.getUserName());
			m.setFullName(Member.getRealName());
			m.setId(Member.getUID());
			m.setCompany(Member.getCompany());
			DataTable CompanyType = new Q(" select * from Mh_Branch where Company = ? and BranchInnerCode = ? ",
					Member.getCompany(), Member.getBranchInnerCode()).fetch();
			String dataTable = new Q(" select IsEngineer from eao_is_engineer where Member = ? ", id).executeString();
			if (!StringUtils.isEmpty(dataTable)) {
				String position = new Q(" select Position from eao_Position where Id = ? ", dataTable).executeString();
				if (!StringUtils.isEmpty(position)) {
					m.setJobType(position);
				}
			}
			this.Response.put("member", m);
			this.Response.put("Menber", Member.getValues());

			MhBranch isEngineer = new MhBranch();
			if (!StringUtils.isEmpty(dataTable) && CompanyType.getRowCount() > 0) {
				isEngineer.setValue(CompanyType.get(0));
				this.Response.put("MhBranch", isEngineer);
			} else {
				this.Response.put("MhBranch", "");
			}
		}
	}

	@Priv(loginType = LoginType.Member)
	public void findById() {
		String id = $V("Id");
		if (id != null) {
			DataTable table = new Q(" select count(*) as count from eao_publicity where IsDelete = 0  and State = 2 and Operator = ?", id).fetch();
			DataTable dataTable = new Q(" select Id , RealName , LogoFile from Ec_Member where ID = ?", id).fetch();
			EaoPublicityMemberVo m = new EaoPublicityMemberVo();
			m.setRealName(dataTable.getString(0, 1));
			m.setId(dataTable.getLong(0, 0));
			m.setCount(table.getString(0, 0));
			m.setPhoto(dataTable.getString(0, "LogoFile"));
			this.Response.put("member", m);
		} else {
			Long tid = Member.getUID();
			DataTable table = new Q(" select count(*) as count from eao_publicity where IsDelete = 0  and State = 2 and Operator = ?", tid).fetch();
			DataTable dataTable = new Q(" select Id , RealName , LogoFile from Ec_Member where ID = ?", tid).fetch();
			EaoPublicityMemberVo m = new EaoPublicityMemberVo();
			m.setRealName(dataTable.getString(0, 1));
			m.setId(dataTable.getLong(0, 0));
			m.setPhoto(dataTable.getString(0, "LogoFile"));
			m.setCount(table.getString(0, 0));
			this.Response.put("member", m);
		}
	}


	/**
	 * 登录人的信息
	 */
	@Priv(loginType = LoginType.Member)
	public void find() {
		String id = $V("Id");
		String newid = $V("Newid");
		String password = $V("Password");
		if (id != null && newid != null) {
			DataTable dataTable = new Q(" select * from Ec_Member where ID = ?", id).fetch();
			EcMember em = new EcMember();
			em.setValue(dataTable.get(0));
			em.setPassword(PasswordUtil.generate(password));
			em.update();
			EaoIsEngineer m = new EaoIsEngineer();
			m.setMember(em.getID().intValue());
			m.setIsEngineer(newid);
			m.insert();
			this.Response.put("MhResource", m);
			this.Response.put("member", em);
			this.Response.put("Menber", Member.getValues());

		}
	}

	/**
	 * 根据id查询人员信息
	 */
	@Priv(login = false)
	public void findByMemberId() {
		String id = $V("Id");
		if (id != null) {
			DataTable people = new Q(" select Mobile , Prop2 , HomePhone from crm_people where Id = ?", id).fetch();
			String Prop2 = null;
			String HomePhone = null;
			String Mobile = null;
			if (people.getRowCount() != 0) {
				Prop2 = people.getString(0, "Prop2");
				HomePhone = people.getString(0, "HomePhone");
				Mobile = people.getString(0, "Mobile");
			}
			Q q = new Q(" select em.*,cp.Prop2 as cp2,br.Name,ep.Position , ei.ImgUrl from Mh_Resource re"
					+ " left JOIN  Ec_Member em on re.Member = em.ID"
					+ " LEFT JOIN  Mh_Branch br on re.BranchInnerCode = br.BranchInnerCode and re.Company = br.Company"
					+ " LEFT JOIN eao_is_engineer eie on em.ID = eie.Member"
					+ " LEFT JOIN crm_people cp on em.ID = cp.Id"
					+ " LEFT JOIN eao_images ei on em.ID = ei.ParentId and ei.Status = '1'"
					+ " LEFT JOIN eao_Position ep on ep.Id = eie.IsEngineer" + " where em.ID = ?", id);
			DataTable dt = q.fetch();
			if (dt.getRowCount() != 0) {
				for (DataRow dataRow : dt) {
					EcMember member = new EcMember();
					member.setValue(dataRow);
					member.setBranchInnerCode(dataRow.getString("Name"));
					member.setJob(dataRow.getString("Position"));
					if (StringUtils.isEmpty(dataRow.getString("ImgUrl"))) {
						member.setProp1(
								"https://ahj-storage-test.oss-cn-beijing.aliyuncs.com/pcfile/2018-12/8d10anull.png?Expires=33080421987&OSSAccessKeyId=LTAIBhKyqEQAbw7q&Signature=vMS3n6mIjo9itkJ437Gui4Krg9c%3D");
					} else {
						member.setProp1(dataRow.getString("ImgUrl"));
					}
					if(StringUtil.isNotEmpty(Prop2)) {
						member.setProp2(dataRow.getString("cp2"));
					}
					if (StringUtil.isNotEmpty(HomePhone)) {
						member.setTel(HomePhone);
					} else {
						member.setTel(Mobile);
					}
					this.Response.put("member", member);
					s("查询成功");
				}
			} else {
				f("没有查到用户信息");
			}
		}
	}

	/**
	 * 获取当前用户创建项目时发送系统消息的人员
	 */
	@Priv(loginType = LoginType.Member)
	public void findByMembers() {
		String charge = $V("Charge");
		String filer = $V("Filer");
		String companyType = new Q(" select CompanyType from Mh_Branch where BranchInnerCode = ? and Company = ?",
				Member.getBranchInnerCode(),Member.getCompany()).executeString();
		String companyType2 = "";
		List<String> code = new ArrayList<>();
		if ("2".equals(companyType)) {
			String ParentInnerCode = new Q(" select ParentInnerCode from Mh_Branch where BranchInnerCode = ? and Company = ?",
					Member.getBranchInnerCode(),Member.getCompany()).executeString();
			DataTable dataTable = new Q(" select BranchInnerCode from Mh_Branch where ParentInnerCode = ? and Company = ?",
					ParentInnerCode,Member.getCompany()).fetch();
			if (dataTable.getRowCount() != 0) {
				for (DataRow dataRow : dataTable) {
					code.add(dataRow.getString(0));
				}
			}
			companyType2 = new Q(" select CompanyType from Mh_Branch where BranchInnerCode = ? and Company = ?", ParentInnerCode,Member.getCompany())
					.executeString();
		}
		String members = null;
		if (("0".equals(companyType) || "0".equals(companyType2) || StringUtil.isNotEmpty(charge))
				&& StringUtils.isEmpty(filer)) {
			DataTable dataTable = new Q(
					" select mr.Member from Mh_Resource mr LEFT JOIN eao_is_engineer ei on mr.Member = ei.Member where mr.Company = ? and ei.IsEngineer in (SELECT id FROM eao_Position where (type = 10 or type is null) and id not in (SELECT parentId FROM eao_Position where type = 10 and ParentId is not null) and (id in ('1','2') or ParentId in ('1','2')))",
					Member.getCompany()).fetch();
			if (dataTable.getRowCount() != 0) {
				for (DataRow dataRow : dataTable) {
					if (StringUtils.isEmpty(members)) {
						members = dataRow.getString(0);
					} else {
						members = members + "," + dataRow.getString(0);
					}
				}
			}
		} else if (("1".equals(companyType) || "1".equals(companyType2)) && StringUtils.isEmpty(charge)
				&& StringUtils.isEmpty(filer)) {
			Q q = new Q(
					" select mr.Member from Mh_Resource mr LEFT JOIN eao_is_engineer ei on mr.Member = ei.Member where mr.Company = ? and ei.IsEngineer in (SELECT id FROM eao_Position where (Type = 10 or Type is null) and Id not in (SELECT ParentId FROM eao_Position where Type = 10 and ParentId is not null) and (Id in ('1','2','3') or ParentId in ('1','2','3')))",
					Member.getCompany());
			q.and().in("BranchInnerCode", code);
			DataTable dataTable = q.fetch();
			if (dataTable.getRowCount() != 0) {
				for (DataRow dataRow : dataTable) {
					if (StringUtils.isEmpty(members)) {
						members = dataRow.getString(0);
					} else {
						members = members + "," + dataRow.getString(0);
					}
				}
			}
		} else if (StringUtil.isNotEmpty(filer)) {
			Q q = new Q(
					" select mr.Member from Mh_Resource mr LEFT JOIN eao_is_engineer ei on mr.Member = ei.Member where mr.Company = ? and ei.IsEngineer = \"7\" ",
					Member.getCompany());
			DataTable dataTable = q.fetch();
			if (dataTable.getRowCount() != 0) {
				for (DataRow dataRow : dataTable) {
					if (StringUtils.isEmpty(members)) {
						members = dataRow.getString(0);
					} else {
						members = members + "," + dataRow.getString(0);
					}
				}
			} else {
				members = Long.toString(Member.getCompany());
			}
		}
		this.Response.put("members", members);
	}

}
